#include <iostream>
#include <thread>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <cstdio>
using namespace std;
void *ThreadRoutine(void *data)
{
    cout << "[" << getpid() << "]: child thread running!" << endl;
    // 子线程处理堆空间数据
    for (int i = 0; i < 10; ++i)
    {
        ((int *)data)[i] = i;
    }
    cout << "[" << getpid() << "]: child thread quit!" << endl;
    // 线程函数返回，线程退出
    return (void *)data; // 返回堆空间的指针
}

int main()
{
    cout << "[" << getpid() << "]: main thread running!" << endl;
    // 创建一批堆区数据
    int *data = new int[10]{0};
    cout << "before: ";
    for (int i = 0; i < 10; ++i)
    {
        cout << data[i] << " ";
    }
    cout << endl;

    pthread_t tid;
    pthread_create(&tid, nullptr, ThreadRoutine, (void *)data);
    int *ret;
    pthread_join(tid, (void **)&ret); // 阻塞等待子线程退出

    // 打印处理后的堆空间数据
    cout << "data change: ";
    for (int i = 0; i < 10; ++i)
    {
        cout << data[i] << " ";
    }
    cout << endl;

    cout << "show ret: ";
    for (int i = 0; i < 10; ++i)
    {
        cout << ret[i] << " ";
    }
    cout << endl;

    cout << "[" << getpid() << "]: main thread quit!" << endl;

    // 释放堆空间
    delete[] data;

    return 0;
}